package com.xkcoding.orm.jdbctemplate.Clickhousejdbctemplate.common.jdbcTemplate;

import com.xkcoding.orm.jdbctemplate.annotation.Column;
import com.xkcoding.orm.jdbctemplate.annotation.Table;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sun.wei
 * @description
 * @date 2023/8/29
 */
public class FindFactory {
    public static String saveSql(Class<?> arg1) {
        // 获取表名
        Table table = (Table) arg1.getAnnotation(Table.class);
        Map<String, Object> p = saveColumn(arg1);
        int arg5 = (int) p.get("COLUMNNUMBER");
        if (arg5 < 1) {
            throw new NullPointerException("column is null");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arg5; i++) {
            if ((i + 1) < arg5) {
                sb.append("?,");
            } else {
                sb.append("?");
            }
        }
        return String.format("INSERT INTO %s ( %s ) VALUES( %s )", table.name(), p.get("COLUMN"), sb.toString());
    }

    private static Map<String, Object> saveColumn(Class<?> arg1) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] arg4 = arg1.getDeclaredFields();
        StringBuffer sb = new StringBuffer();
        int arg4Size = arg4.length;
        for (int i = 0; i < arg4Size; i++) {
            Field arg5 = arg4[i];
            Column column = arg5.getAnnotation(Column.class);
            // Id id = arg5.getAnnotation(Id.class);
            if (column != null) {
                sb.append(column.name());
                sb.append(",");
                atomicInteger.getAndIncrement();
            }
        }
        map.put("COLUMN", sb.toString().replaceFirst(",$", ""));
        map.put("COLUMNNUMBER", atomicInteger.get());
        return map;
    }
}
